<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="label">联系人:</div>
      <el-input v-model="listQuery.name" placeholder="输入联系人姓名" style="width: 200px;" class="filter-item" />

      <div class="label">手机号码:</div>
      <el-input v-model="listQuery.mobile" placeholder="输入联系人手机号" style="width: 200px;" class="filter-item" />

      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate()"
      >
        新增
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch()"
      >
        重置
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch()"
      >
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column label="单位" prop="unit" align="center" min-width="100">
        <template slot-scope="{ row }">
          <span>{{ row.unit }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系人" prop="name" align="center" width="120">
        <template slot-scope="{ row }">
          <span class="link-type" @click="handleUpdate(row)">{{
            row.name
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" min-width="140px">
        <template slot-scope="{ row }">
          <span>{{ row.province }}{{ row.city }}{{ row.district }}{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" width="120" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.lastUpdateUserName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" width="180" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.lastUpdateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="80px" style="width: 450px;">
        <el-form-item label="单位">
          <el-input v-model="temp.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-input v-model="temp.name" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="temp.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-row>
          <el-col style="width: 200px;">
            <el-form-item label="省市区" prop="province">
              <el-select v-model="temp.province" placeholder="请选择省份" size="mini" value-key="id">
                <el-option
                  v-for="(item, index) in provinceOption"
                  :key="index"
                  :label="item.areaName"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col style="width: 110px;margin-left: 15px;">
            <el-form-item prop="city" label-width="10">
              <el-select v-model="temp.city" placeholder="请选择城市" size="mini" value-key="id">
                <el-option
                  v-for="(item, index) in cityOption"
                  :key="index"
                  :label="item.areaName"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col style="width: 110px;margin-left: 15px;">
            <el-form-item prop="district" label-width="10">
              <el-select v-model="temp.district" placeholder="请选择区县" size="mini" value-key="id">
                <el-option
                  v-for="(item, index) in districtOption"
                  :key="index"
                  :label="item.areaName"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="createData()"> 提交 </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  fetchContactList,
  delContact,
  createContact,
  editContact
} from '@/api/tms/contact.js'
import {
  selector
} from '@/api/iam/area.js'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import {
  parseTime
} from '@/utils'

export default {
  name: 'ComplexTable',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      provinceOption: [],
      cityOption: [],
      districtOption: [],
      listQuery: {
        current: 1,
        size: 20,
        name: undefined,
        mobile: undefined
      },
      temp: {
        id: undefined,
        unit: '',
        name: '',
        mobile: '',
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        district: '',
        districtCode: '',
        info: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑联系人',
        create: '新增联系人'
      },
      pvData: [],
      rules: {
        name: [{
          required: true,
          message: '请填写联系人',
          trigger: 'change'
        }],
        mobile: [{
          required: true,
          message: '请填写手机号码',
          trigger: 'blur'
        }],
        province: [{
          required: true,
          message: '请选择省',
          trigger: 'blur'
        }],
        city: [{
          required: true,
          message: '请选择市',
          trigger: 'blur'
        }],
        district: [{
          required: true,
          message: '请选择区/县',
          trigger: 'blur'
        }],
        address: [{
          required: true,
          message: '请填写详细地址',
          trigger: 'blur'
        }]
      },
      timeFrame: null
    }
  },
  watch: {
    'temp.province'(e) {
      this.temp.city = {}
      this.temp.district = {}
      if (e && e.code) {
        this.temp.provinceCode = e.id
        this.temp.province = e.areaName
        this.handleGetCityList(e.id)
      }
    },
    'temp.city'(e) {
      this.temp.district = {}
      if (e && e.code) {
        this.temp.cityCode = e.id
        this.temp.city = e.areaName
        this.handleGetAreaList(e.id)
      }
    },
    'temp.district'(e) {
      if (e && e.code) {
        this.temp.district = e.areaName
        this.temp.districtCode = e.id
      }
    }
  },
  created() {
    this.getList()
    this.handleGetProvinceList()
  },
  methods: {
    handleGetProvinceList() {
      // 获取省
      selector({ 'areaParentId': 100000 }).then((response) => {
        this.provinceOption = response
      })
    },
    handleGetCityList(parentId) {
      // 获取市
      selector({
        'areaParentId': parentId
      }).then((response) => {
        this.cityOption = response
      })
    },
    handleGetAreaList(parentId) {
      // 获取区
      selector({
        'areaParentId': parentId
      }).then((response) => {
        this.districtOption = response
      })
    },
    getList() {
      this.listLoading = true
      fetchContactList(this.listQuery).then((response) => {
        console.log(response)
        this.list = response.records
        this.total = response.total
        this.listLoading = false
      })
    },
    // 搜索
    handleSearch() {
      this.listQuery.current = 1
      this.getList()
    },
    sortChange(data) {},
    // 重置表单内容
    resetTemp() {
      this.temp = {
        id: undefined,
        unit: '',
        name: '',
        mobile: '',
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        district: '',
        districtCode: '',
        info: ''
      }
    },
    resetSearch() {
      this.listQuery = {
        current: 1,
        size: 20,
        name: undefined,
        mobile: undefined
      }
    },
    // 新增弹窗
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新或者新增
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          if (this.dialogStatus === 'create') {
            createContact(this.temp).then((res) => {
              this.getList()
              this.dialogFormVisible = false
              const msg = '添加成功'
              this.$notify({
                title: '成功',
                message: msg,
                type: 'success',
                duration: 2000
              })
            })
          } else {
            editContact(this.temp).then((res) => {
              this.getList()
              this.dialogFormVisible = false
              const msg = '编辑成功'
              this.$notify({
                title: '成功',
                message: msg,
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    // 更新弹窗
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 处理删除选项
    handleDelete(row) {
      const arr = []
      arr.push(row.id)
      const data = {
        'ids': arr
      }
      delContact(data).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss">
	.filter-container {
		display: flex;
		justify-content: flex-end;
		align-items: center;

		.filter-item {
			margin-bottom: 0px;
		}

		.align-items {
			margin-bottom: 0;
		}

		.label {
			margin-right: 10px;
			margin-left: 10px;
		}
	}

	.dialog-footer {
		display: flex;
		align-items: center;
		justify-content: center;

		button {
			width: 100px;
		}
	}

	.content {
		margin-left: 0px;
		display: flex;

		.val {
			flex: 1;
		}

		.label {
			width: 30px;
			text-align: center;
		}
	}
</style>
